from apps.minapp import models
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, \
    DestroyModelMixin
from rest_framework import serializers
from apps.minapp.views.goods import CoverSerializer
from django.db.models import Sum, F
from django.db import models as dbmodel


def carthandle(queryset, serializer):
    result = []
    print(queryset)
    for cart in queryset:
        existed = False
        for item in result:
            if cart.goods.detail.shop_id == item['shop_id']:
                item['carts'].append(serializer(cart).data)
                existed = True
                break
        if not existed:
            temp = {'shop_id': cart.goods.detail.shop_id, 'shop_name': cart.goods.detail.shop.title, 'carts': []}
            temp['carts'].append(serializer(cart).data)
            result.append(temp)
    print(result)
    return result


class CartDetailSerializer(serializers.ModelSerializer):
    goods = CoverSerializer()

    class Meta:
        model = models.ShoppingCart
        exclude = ['user']
        depth = 1


class CartView(DestroyModelMixin, RetrieveModelMixin, CreateModelMixin, UpdateModelMixin, GenericViewSet):
    queryset = models.ShoppingCart.objects.all()
    serializer_class = CartDetailSerializer

    def get_queryset(self):
        return models.ShoppingCart.objects.filter(user_id=self.request.user.id, deleted=False)

    def retrieve(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        result = carthandle(queryset, CartDetailSerializer)
        return Response(result)

    def create(self, request, *args, **kwargs):
        print(request.user)
        data = request.data
        print(data)
        goods_id = data['goods_id']
        existed = self.get_queryset().filter(goods_id=goods_id, deleted=False)
        # 判断当前是否已有记录
        if existed:
            existed = existed[0]
            existed.num += 1
            existed.save()
        else:
            models.ShoppingCart.objects.create(user_id=self.request.user.id, **data)
        return Response("添加成功")

    def update(self, request, *args, **kwargs):
        data = request.data
        print(data)
        cart_id = kwargs['pk']
        cart = models.ShoppingCart.objects.get(id=cart_id)
        cart.__dict__.update(**data)
        cart.save()
        return Response("修改成功")

    def destroy(self, request, *args, **kwargs):
        print(request.data)
        pks = request.data
        models.ShoppingCart.objects.filter(pk__in=pks).update(deleted=True)
        return Response("成功删除商品")


# 用户————结算购物车
class CartSettleView(RetrieveModelMixin, GenericViewSet):
    queryset = models.ShoppingCart.objects.all()
    serializer_class = CartDetailSerializer

    def get_queryset(self):
        return models.ShoppingCart.objects.filter(user_id=self.request.user.id, deleted=False)

    def retrieve(self, request, *args, **kwargs):
        queryset = self.get_queryset().filter(checked=True)
        total_amount = queryset.aggregate(
            sum=Sum(F('goods__price') * F('num'), output_field=dbmodel.DecimalField(decimal_places=2, max_digits=6)))[
            'sum']
        print(total_amount)
        total_count = queryset.aggregate(sum=Sum('num'))['sum']
        result = carthandle(queryset, CartDetailSerializer)
        print(total_count)
        return Response({'shoporders': result, 'total_amount': total_amount, 'total_count': total_count})
